import React, { useRef, useState } from "react";
import { Button, Form, Input, Space, message } from "antd";
import { LockOutlined, UserOutlined, KeyOutlined } from "@ant-design/icons";
import Captcha from "./Captcha";
import axios from "../service/index";
import { useHistory } from "react-router-dom";

export default function Normal() {
  let child = useRef();
  let [key, setKey] = useState("");
  let history = useHistory();
  const onFinish = (values) => {
    // console.log("Success:", values);
    values.key = key; 
    // 登录需要4个参数：
    axios.post("/api/common/auth/login", values).then((res) => {
      if (res.errNo === 0) {
        history.push("/dashboard");
      } else {
        console.log(res);
        message.error(res.errText, 1);
        child.current.getCode(); // 调用子组件的方法： 登录失败，重新刷新验证码
      }
    });
  };
  return (
    <div>
      <Form onFinish={onFinish}>
        <Form.Item
          name="username"
          rules={[
            {
              required: true,
              message: "Please input your username!",
            },
          ]}
        >
          <Input prefix={<UserOutlined className="site-form-item-icon" />} />
        </Form.Item>

        <Form.Item
          name="password"
          rules={[
            {
              required: true,
              message: "Please input your password!",
            },
          ]}
        >
          <Input.Password
            prefix={<LockOutlined className="site-form-item-icon" />}
          />
        </Form.Item>
        <Form.Item
          name="captcha"
          rules={[
            {
              required: true,
              message: "Please input your captcha!",
            },
          ]}
        >
          <Space>
            <Input prefix={<KeyOutlined className="site-form-item-icon" />} />
            <Captcha setKey={setKey} ref={child}></Captcha>
          </Space>
        </Form.Item>
        <Form.Item>
          <Button
            type="primary"
            htmlType="submit"
            className="login-form-button"
          >
            登录
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
}
